package lime.xquery.widget;

import java.io.ByteArrayOutputStream;

import lime.common.DOMUtils;
import lime.common.UIUtils;

import org.apache.commons.io.IOUtils;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.w3c.dom.Document;

public class XQueryXmlResult extends Composite {

	public XQueryXmlResult(Composite parent, int style) {
		super(parent, style);
		init();
	}

	private void init() {
		this.setLayout(new FillLayout());
	}
	
	public void update(final String paramText) {

		UIUtils.clear(this);
		
		String text = paramText;
	
		try {
			Document doc = DOMUtils.parse(text);
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			DOMUtils.serialize(doc, outputStream);
			text = new String(outputStream.toByteArray(), "utf-8");
			IOUtils.closeQuietly(outputStream);
		} catch (Exception e) {
			text = e.getMessage();
			e.printStackTrace();
		} 
		
		Text resultText = new Text(this, SWT.WRAP | SWT.MULTI | SWT.V_SCROLL);
		resultText.setFont(JFaceResources.getTextFont());
		resultText.setText(text);
		
		this.layout();
	}
	
}
